﻿var parentid = 0;
var regions = {};
var currentid = 0;
var oparentid = 0;
$(function() {
    var _allcatalog = $(".treemenu a");
    showregions(_allcatalog);
    bindEvent1(_allcatalog);

    $("#dialog").dialog({
        autoOpen: false,
        width: 400,
        dialogClass: "my-dialog",
        modal: false,
        resizable: false
    });

    $("#btn_close").click(function() {
        $("#dialog").dialog("close");
    });

    BindCheckBoxEvent($("#btn_delete"));

    $("#lbtn_create").click(function() {
        $("#dialog").dialog("open");
        $("#dialog").dialog("option", "title", '添加地区');
        $("#btn_submit").val("添加");
        $("#txt_regionname").val("");
        return false;
    });
    $("#btn_submit").click(function() {
        bindSubmitEvent();
    });
    $("#btn_delete").click(function() {
        bindMulDeleteEvent();
    });
    $("#lbtn_sorting").click(function() {
        $(".dg tbody").sortable();
        $(".dg tbody").sortable("option", "disabled", false);
        $(".dg tbody").sortable("option", "cursor", "move");

        $("#btn_delete").hide();
        $("#btn_save,#btn_cancel,.warning").show();
        formReady();
        return false;
    });
    $("#btn_save").click(function() {
        doSorting();
    });
    $("#btn_cancel").click(function() {
        $(".dg tbody").sortable("option", "disabled", true);

        $("#btn_delete").show();
        $("#btn_save,#btn_cancel,.warning").hide();
    });

    $(".dv_content").show();
    formReady();
});
function genarateHtml(obj) {
    var data = regions["rid" + parentid];
    if (data != null) {
        var newul = $("<ul/>");
        $(".dg tbody").empty();
        $.each(data, function(i, item) {
            //创建树型菜单的内容
            appendToMenu(newul, item);

            //创建Table的内容
            appendToTable(i, item);
        });
        $(".dg tbody tr").hover(function() { $(this).addClass("tdmover"); }, function() { $(this).removeClass("tdmover"); });
        if (obj.next().length == 0) {
            obj.after(newul);
        }
        else {
            obj.next().show();
        }
    }

    formReady();
}
function showregions(obj) {
    if (regions["rid" + parentid] == null) {
        $.ajax({
            type: "GET",
            url: rootpath + "api/region.ashx",
            data: { type: 'getCity', pid: parentid, r: Math.random() },
            dataType: "json",
            success: function(data) {
                regions["rid" + parentid] = data;
                genarateHtml(obj);
            }
        });
    }
    else {
        genarateHtml(obj);
    }
}
function appendToTable(i, item) {
    i++;
    var cb = "<input type='checkbox' value='" + item.rid + "' />";
    var delbutton = "&nbsp;<input type='button' class='deleteButton' rel='" + item.rid + "' />";
    if (item.childnum > 0) {
        cb = "";
        delbutton = "";
    }

    $(".dg tbody").append("<tr> \
                        <td>" + cb + "</td> \
                        <td>" + i + "</td> \
                        <td>" + item.rname + "</td> \
                        <td><input type='button' class='editButton' rel='" + item.rid + "' />" + delbutton + "</td> \
                    </tr>");

    bindButtonEvent($(".editButton:last"));

    if (cb.length > 0) {
        BindCheckBox($("#btn_delete"), $(":checkbox:last"));
    }
    if (delbutton.length > 0) {
        bindDeleteEvent($(".deleteButton:last"));
    }
}
function appendToMenu(obj, item) {
    var classname = "w";
    if (item.childnum > 0) {
        classname = "r";
    }
    var newli = $("<li/>");
    newli.append('<a href=\"#" class="' + classname + '" rel="' + item.rid + '">' + item.rname + '</a>');
    obj.append(newli);
    var _this = newli.find("a");
    if (item.childnum > 0) {
        bindEvent1(_this);
    }
    else {
        bindEvent2(_this);
    }
}
function bindEvent1(_this) {
    _this.click(function() {
        resetStatus(_this);

        $(".treemenu .current").removeClass("current");
        _this.addClass("current");

        showregions(_this);
        if (_this.hasClass("r")) {
            _this.addClass("b");
            _this.removeClass("r");
        }
        else {
            _this.addClass("r");
            _this.removeClass("b");
            _this.next().hide();
        }
        return false;
    });
}
function bindEvent2(_this) {
    _this.click(function() {
        resetStatus(_this);
        $(".dg tbody").empty();
        $(".treemenu .current").removeClass("current");
        $(this).addClass("current");
        return false;
    });
}
function bindButtonEvent(_this) {
    var _tr = _this.parents("tr")
    _this.click(function() {
        $("#txt_regionname").val(_tr.find("td").eq(2).html());
        $("#dialog").dialog("open");
        $("#dialog").dialog("option", "title", '修改地区');
        $("#btn_submit").val("修改");
        currentid = _this.attr("rel");
        oparentid = $(".treemenu .current").attr("rel");
    });
}
function resetStatus(_this) {
    if (_this) {
        parentid = _this.attr("rel");
        parentname = _this.html();
        if (parentname == "全国地区") {
            parentname = "";
        }
        $("#txt_parentname").val(parentname);
    }
    $("#cb_All").attr("checked", "");
    $("#btn_delete").attr("disabled", "diabled");
}
function bindSubmitEvent() {
    var regionname = $('#txt_regionname').val();
    var parentRname = $('#txt_parentname').val();
    if (regionname.length == 0) {
        if ($('#txt_regionname').next("span").length == 0) {
            $('#txt_regionname').after("<span style='color:red;'>地区名字不能为空！</span>");
        }
        else {
            $('#txt_regionname').next().show();
        }
        return;
    }

    if (regionname.length == 0) {
        if ($('#txt_parentname').next("span").length == 0) {
            $('#txt_parentname').after("<span style='color:red;'>地区描述！</span>");
        }
        else {
            $('#txt_parentname').next().show();
        }
        return;
    }
    
    $("#btn_submit").attr("disabled", "disabled").after("<span>提交中.....</span>");

    var data = { type: 'add', aname: regionname, apid: parentid,r: Math.random() };

    if (currentid > 0) {
        data = { type: 'update', uname: regionname, urid: currentid, upid: parentid, opid: oparentid, r: Math.random() };
    }

    $.ajax({
        type: "POST",
        url: rootpath + "api/region.ashx",
        data: data,
        dataType: "string",
        success: function(data) {

            if (currentid > 0) {
                if (data > 0) {
                    $("#dialog").dialog("close");
                    facebox("地区修改成功！");

                    $(".editButton[rel='" + currentid + "']").parents("tr").find("td").eq(2).html(regionname);
                    $(".treemenu a[rel='" + currentid + "']").html(regionname);

                    resetData(regionname);

                    currentid = 0;
                    oparentid = 0;
                    $("#txt_regionname").val("");
                    $("#txt_parentname").val("");
                }
                else if (data == -1) {
                    facebox("不能将地区移至自己的子地区！");
                }
                else {
                    facebox("地区信息修改失败！");
                }
            }
            else {
                if (data > 0) {
                    $("#dialog").dialog("close");
                    facebox("地区信息创建成功！");

                    var item = { rid: data, rname: regionname, pid: parentid, childnum: 0};

                    addItem(parentid, item);
                    resetCache(parentid, 1);
                    resetMenu(item);
                    appendToTable($(".dg tbody tr").length, item);

                    $("#txt_regionname").val("");
                    formReady();
                }
                else {
                    facebox("地区信息创建失败！");
                }
            }
            $("#btn_submit").attr("disabled", "").next("span").remove();
        }
    });
}
function bindMulDeleteEvent() {
    confirmbox("确定要删除所有选中地区吗？");

    $(window.parent.document).find("#btn_sure").click(function() {
        closebox();

        var cids = "";
        $("input:checked").not("#cb_All").each(function() {
            cids += $(this).val() + ",";
        });

        doDelete(cids);
    });
}
function bindDeleteEvent(_this) {
    _this.click(function() {
        confirmbox("确定要删除当前地区吗？");
        $(window.parent.document).find("#btn_sure").click(function() {
            closebox();
            doDelete(_this.attr("rel"));
        });
    });
}
function doDelete(cids) {
    $.ajax({
        type: "POST",
        url: rootpath + "api/region.ashx",
        data: { type: 'del', pid: parentid, sids: cids, r: Math.random() },
        dataType: "string",
        success: function(data) {
            if (data == 1) {
                facebox("操作已完成！");

                var _cids = cids.split(',');

                for (var i = 0; i < _cids.length; i++) {
                    var rid = _cids[i];
                    if (rid != "") {
                        removeTr(rid);
                        removeMenu(rid);
                        removeItem(rid, parentid);
                        resetCache(parentid, -1);
                    }
                }
                resetStatus();
            }
        }
    });
}
function doSorting() {
    var rids = "";
    $(".dg tbody .editButton").each(function() {
        rids += $(this).attr("rel") + ",";
    });
    $.ajax({
        type: "POST",
        url: rootpath + "api/region.ashx",
        data: { type: 'sorting', rids: rids, r: Math.random() },
        dataType: "string",
        success: function(data) {
            if (data == 1) {
                facebox("操作已完成！");

                $(".dg tbody").sortable("option", "disabled", true);

                $("#btn_delete").show();
                $("#btn_save,#btn_cancel,.warning").hide();

                updateSorting(rids);
            }
        }
    });
}
function removeTr(rid) {
    $(".deleteButton[rel='" + rid + "']").parents("tr").eq(0).remove();
}
function removeMenu(rid) {
    var parentli = $(".treemenu a[rel='" + rid + "']").parent();

    if (parentli.siblings().length == 0) {
        var _a = parentli.parent().prev();
        _a.removeClass("b").addClass("w").unbind("click");
        bindEvent2(_a);

        parentli.parent().remove();
    }
    else {
        parentli.remove();
    }
}
function resetData(rname) {
    var item = updateItem(oparentid, currentid, rname, null);

    resetCache(oparentid, -1);
    resetCache(parentid, 1);

    if (oparentid != parentid) {
        removeItem(currentid, oparentid);
        addItem(parentid, item);
        removeMenu(currentid);
        resetMenu(item);
        appendToTable($(".dg tbody tr").length, item);
    }
}
function resetCache(pid, val) {

    var ancestor = $(".treemenu a[rel='" + pid + "']").parents("ul").eq(0).prev().attr("rel");

    if (regions["rid" + ancestor] != null) {
        $.each(regions["rid" + ancestor], function(i, item) {
            if (item.rid == pid) {
                item.childnum = parseInt(item.childnum) + val;
            }
        });
    }
}
function resetMenu(item) {

    var _current = $(".treemenu .current");
    var newul = _current.next();

    if (newul.length == 0) {
        newul = $("<ul/>");
        _current.after(newul).removeClass("w").addClass("b").unbind("click");
        bindEvent1(_current);
    }

    appendToMenu(newul, item);
}
function removeItem(rid, pid) {

    var newdata = [];

    $.each(regions["rid" + pid], function(i, item) {
        if (item.rid != rid) {
            newdata.push(item);
        }
    });

    regions["rid" + pid] = newdata;
}
function addItem(rid, item) {
    if (regions["rid" + parentid] == null) {
        regions["rid" + rid] = [];
    }
    regions["rid" + parentid].push(item);
}
function updateItem(pid, rid, rname, seq) {
    var ritem = {};
    var data = regions["rid" + pid];

    $.each(data, function(i, item) {
        if (item.rid == rid) {
            if (rname != null)
                item.rname = rname;
            if (seq != null) {
                item.seq = seq;
            }
            ritem = item;
        }
    });
    return ritem;
}
function updateSorting(rids) {
    var _rids = rids.split(',');
    for (var i = 0; i < _rids.length; i++) {
        var rid = _rids[i];
        if (rid != "") {
            updateItem(parentid, rid, null, i * 10);
        }
    }
    regions["rid" + parentid].sort(function(a, b) { return a["seq"] > b["seq"] ? 1 : a["seq"] == b["seq"] ? 0 : -1 });

    reBuildMenu();
}
function reBuildMenu() {
    var _ul = $(".treemenu .current").next();
    _ul.empty();
    var data = regions["rid" + parentid];

    $.each(data, function(i, item) {
        appendToMenu(_ul, item);
    });
}
